package com.csxh.web.handler.eshop;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.csxh.web.model.BuyCart;
import com.csxh.web.model.BuyItem;
import com.csxh.web.model.eshop.Customer;
import com.csxh.web.model.eshop.Order;
import com.csxh.web.model.eshop.Orderdetail;
import com.csxh.web.model.eshop.Paymethod;
import com.csxh.web.model.eshop.Shipping;
import com.csxh.web.service.eshop.OrderService;
import com.csxh.web.service.eshop.OrderdetailService;
import com.csxh.web.service.eshop.PaymethodService;
import com.csxh.web.service.eshop.ShippingService;
import com.csxh.web.util.servlet.WebUtil;


@Controller
public class OrderHandler {

	@Autowired
	private OrderService orderService;
	
	@Autowired
	private OrderdetailService orderdetailService;
	
	@Autowired
	private PaymethodService paymethodService;
	
	@Autowired
	private ShippingService shippingService;
	
	
	@RequestMapping("/order")
	public String showOrderForm(HttpServletRequest request) {
		//准备支付
		List<Shipping> shippingList=shippingService.findAll();
		request.setAttribute("shippingList", shippingList);
		
		//付款
		List<Paymethod> paymethodList=paymethodService.findAll();
		request.setAttribute("paymethodList", paymethodList);
		
		return "order";
	}
	@SuppressWarnings("unchecked")
	@RequestMapping("/order/add")
	public String submitOrderForm(HttpServletRequest request) {
		//一定会拿到用户对象
		Customer c=WebUtil.getUser(request);
		BuyCart<BuyItem> b=WebUtil.getBuyCart(request, BuyCart.class);
		
		Order order=new Order();
		
		order.setCustomerId(c.getId());
		order.setDeliverAddres(c.getAddress());
		order.setDeliverCity(c.getCity());
		order.setDeliverName(c.getRealname());
		order.setDeliverPhone(c.getPhone());
		order.setDeliverZip(c.getZip());
		order.setFulfilled(false);
		
		//订单编号：使用用户id+下单的时间
		String orderNumber=java.util.UUID.randomUUID().toString();
		order.setOrderNumber(orderNumber);
		
		//OrderService.save(order);
		
		//创建订单明细
		for(BuyItem item:b.getItemList()){
			
			Orderdetail od=new Orderdetail();
			
			od.setOrderNumber(orderNumber);
			od.setProductIsbn(item.getIsbn());
			od.setProductName(item.getName());
			od.setQuantity(item.getQuantity());
			od.setUnitPrice(item.getUnitWeight());
			od.setTotalPrice(item.getTotalPrice());

			//OrderdetailService.save(od);
			
		}
		return "cart";
	}

}
